package org.deng.learn.zookeeper.simple;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.List;

/**
 * @Author DengLibin
 * @Date 19-5-12
 * @Time 下午5:15
 * @Desc 服务器上下线监听器
 */
public class ServerListener {
    //服务器集群
    private static String servers = "node2:2181,node3:2181,node4:2181";
    private String serverNodeParentPath; //要监听的服务器注册到zookeeper的节点的父节点
    //zookeeper客户端
    private ZooKeeper client;

    private volatile boolean isListening = false;

    public ServerListener(String serverNodeParentPath) {
        this.serverNodeParentPath = serverNodeParentPath;
    }

    /**
     * 连接到zookeeper
     * @throws IOException
     */
    private    void connectZookeeper() throws IOException {
        client = new ZooKeeper(servers, 2 * 1000, event -> {

           // System.out.println("监听事件:"+event.getPath() +","+event.getType().name()+","+event.getType());
            if(event.getPath() != null && event.getType() == Watcher.Event.EventType.NodeChildrenChanged){
                List<String> children = null;
                try {
                    children = client.getChildren(event.getPath(), true);
                    System.out.println("当前服务器节点:");
                    for(String child : children){
                        byte[] data = client.getData(serverNodeParentPath + "/" + child, false, null);
                        System.out.println(child +"-->"+new String(data));
                    }
                    registerListen(); //再次注册监听
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 注册监听
     */
    private   void registerListen() throws KeeperException, InterruptedException {
         client.getChildren(serverNodeParentPath, true);
    }

    /**
     * 开始监听
     * @throws InterruptedException
     * @throws KeeperException
     */
    public void startListen() throws InterruptedException, KeeperException, IOException {
        new Thread(()->{
            isListening = true;
            try {
                connectZookeeper();
                registerListen();
                while (isListening){
                    Thread.sleep(1000 * 1000);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }).start();

    }

    /**
     * 停止监听
     */
    public  void stopListen() throws InterruptedException {
        isListening = false;
        client.close();
    }

}
